//
//  IAAAuthCheckSureVC.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/13.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAAAuthCheckSureVC.h"
#import "IAAAuthCheSecCheckerVC.h"
#import "IAAAuthCheckModel.h"
#import "MD5Algorithm.h"

@interface IAAAuthCheckSureVC ()

@property (weak, nonatomic) IBOutlet UITextView *textView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secCheckerBgViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *secCheckerBgViewTop;
@property (weak, nonatomic) IBOutlet UIView *secCheckerBgView;
@property (weak, nonatomic) IBOutlet UILabel *secCheckerLabel;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *phoneNumBgViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *phoneNumBgViewTop;
@property (weak, nonatomic) IBOutlet UIView *phoneNumBgView;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marketBgViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marketBgViewTop;
@property (weak, nonatomic) IBOutlet UIView *marketBgView;
@property (weak, nonatomic) IBOutlet UITextField *marketTextField;

@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *passBtn;
@property (weak, nonatomic) IBOutlet UIButton *notPassBtn;

@property (strong, nonatomic) IAAAuthCheckCheckerItem *checkerItem;
@property (strong, nonatomic) IAAAuChPhoneCodeModel *phoneModel;

@end

@implementation IAAAuthCheckSureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //设置导航栏
    [self initNavigationBar];
    //設置子Views
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)initNavigationBar {
    self.navigationItem.title = (self.taskItem.taskLevel == 11) ? @"一审" : @"二审";
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭"
                                                                  style:UIBarButtonItemStylePlain
                                                                 target:self
                                                                 action:@selector(rightBarBtnItemTapped:)];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)initSubViews {
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    self.textView.layer.cornerRadius = 4;
    self.textView.layer.borderColor = IAA_COLOR_0xE0E0E0(1.0).CGColor;
    self.textView.layer.borderWidth = 1;
    self.textView.layer.masksToBounds = YES;
    self.textView.text = self.commitModel.failReason;
    
    self.secCheckerLabel.layer.cornerRadius = 4;
    self.secCheckerLabel.layer.borderColor = IAA_COLOR_0xE0E0E0(1.0).CGColor;
    self.secCheckerLabel.layer.borderWidth = 1;
    self.secCheckerLabel.layer.masksToBounds = YES;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                 action:@selector(selSecCheckerTapped:)];
    [self.secCheckerLabel addGestureRecognizer:tapGesture];
    
    // 二审柜员号
    if (!(self.taskItem.taskLevel == IAAAuChTaskLevelFirst && self.taskItem.isNeedSecCheck)) {
        self.secCheckerBgView.hidden = YES;
        self.secCheckerBgViewTop.constant = 0;
        self.secCheckerBgViewHeight.constant = 0;
    }
    self.secCheckerLabel.text = self.commitModel.nuserNo;
    
    // 手机验证码
    if (self.taskItem.taskLevel != IAAAuChTaskLevelSecond) {
        self.phoneNumBgView.hidden = YES;
        self.phoneNumBgViewTop.constant = 0;
        self.phoneNumBgViewHeight.constant = 0;
    }
    self.phoneNumTextField.text = self.commitModel.verifyCode;
    
    // 营销识别码
    if (self.taskItem.taskLevel != IAAAuChTaskLevelFirst) {
        self.marketBgView.hidden = YES;
        self.marketBgViewTop.constant = 0;
        self.marketBgViewHeight.constant = 0;
    }
    self.marketTextField.text = self.commitModel.marketingCode;
    
    self.getCodeBtn.layer.cornerRadius = 4;
    self.getCodeBtn.layer.masksToBounds = YES;
    self.passBtn.layer.cornerRadius = 4;
    self.passBtn.layer.masksToBounds = YES;
    self.notPassBtn.layer.cornerRadius = 4;
    self.notPassBtn.layer.masksToBounds = YES;
    [self.getCodeBtn addTarget:self action:@selector(getCodeBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.passBtn addTarget:self action:@selector(passBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.notPassBtn addTarget:self action:@selector(notPassBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)refreshWholeView {
    self.secCheckerLabel.text = self.checkerItem.userNo;
}

#pragma mark - 按键处理
- (void)rightBarBtnItemTapped:(UIBarButtonItem *)item {
    [self saveUserInputToModel];
    if (self.auChSureHandle) {
        self.auChSureHandle(AuChSureResultClose);
        self.auChSureHandle = nil;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)selSecCheckerTapped:(UIGestureRecognizer *)gesture {
    IAAAuthCheSecCheckerVC * vc =[[IAAAuthCheSecCheckerVC alloc] init];
    vc.getSecChecker = ^(IAAAuthCheckCheckerItem *item){
        self.checkerItem = item;
        [self refreshWholeView];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)getCodeBtnTapped:(UIButton *)btn {
    [self startTime];
    [self requestVerifyCode];
}

- (void)passBtnTapped:(UIButton *)btn {
    [self saveUserInputToModel];
    
    // 校验是否有照片没有补拍
    if (![self checkForceReTakePicture]) {
        return;
    }
    
    // 校验用户输入
    if (![self checkUserInput:btn]) {
        return;
    }
    
    // 上传图片、提交审核
    [self requestUploadPicture:YES];
}

- (void)notPassBtnTapped:(UIButton *)btn {
    [self saveUserInputToModel];
    if (![self checkUserInput:btn]) {
        return;
    }
    // 上传图片、提交审核
    [self requestUploadPicture:NO];
}

- (BOOL)checkForceReTakePicture {
    IAAAuthCheckImgItem *item =[self.auChModel forceReTakePicture];
    if (item) {
        NSInteger index = [self.auChModel.imgelist indexOfObject:item];
        NSString *message = [NSString stringWithFormat:@"第%zd个%@需要重新拍摄", index + 1, item.imageName];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"补拍"
                                                                                 message:message
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return NO;
    }
    return YES;
}

- (BOOL)checkUserInput:(UIButton *)btn {
    BOOL commitFlag = (btn == self.passBtn);
    // 理由
    if (!commitFlag && !self.textView.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入审核不通过的理由"];
        return NO;
    }
    
    // 二审柜员号
    if (self.taskItem.taskLevel == IAAAuChTaskLevelFirst && self.taskItem.isNeedSecCheck && !self.secCheckerLabel.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择二审柜员号"];
        return NO;
    }
    
    // 手机验证码
    if (commitFlag && self.taskItem.taskLevel == IAAAuChTaskLevelSecond && !self.phoneNumTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入手机验证码"];
        return NO;
    }
    
    // 营销识别码
    if (commitFlag && self.taskItem.taskLevel == IAAAuChTaskLevelFirst && !self.marketTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入营销识别码"];
        return NO;
    }
    
    // 密码
    if (!self.pwdTextField.text.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入密码"];
        return NO;
    }
    
    return YES;
}

- (void)saveUserInputToModel {
    self.commitModel.failReason = self.textView.text;
    self.commitModel.marketingCode = self.marketTextField.text;
    if (self.checkerItem) {
        self.commitModel.norgNo = self.checkerItem.orgNo;
        self.commitModel.nuserNo = self.checkerItem.userNo;
    }
    if ([self.phoneModel.resultCode isEqualToString:IAA_RESULT_CODE_SUC]) {
        self.commitModel.userStr = self.phoneModel.userStr;
    }
}

#pragma mark - 开始计时器
-(void)startTime{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.getCodeBtn setBackgroundColor:IAA_COLOR_0x129CFF(1.0)];
                [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.getCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 60 ;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [self.getCodeBtn setBackgroundColor:[UIColor grayColor]];
                [self.getCodeBtn setTitle:[NSString stringWithFormat:@"重新发送(%@s)",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                self.getCodeBtn.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - 网络请求
// 获取手机验证码
- (void)requestVerifyCode {
    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckGetVerifyCode];
    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
                           @"userNo" : IAA_APP_DELEGATE.userNo,
                           @"osName" : @"iOS",
                           @"busiId" : self.taskItem.busiId,
                           @"token"  : IAA_APP_DELEGATE.token};
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取手机验证码返回%@", responseObject);
        [hud hide:NO];
        self.phoneModel = [IAAAuChPhoneCodeModel yy_modelWithJSON:responseObject];
        if ([self.phoneModel.resultCode isEqualToString:IAA_RESULT_CODE_SUC]) {
            [self saveUserInputToModel];
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"验证码已发送"];
        }else{
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"resultMsg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取手机验证码失败%@", error);
        [hud hide:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

// 上传补拍的照片
- (void)requestUploadPicture:(BOOL)commitFlag {
    if (![self.auChModel isNeedUploadPicture]) {
        [self requestCommitTask:commitFlag];
        return;
    }
    
    IAAAuChUploadPicModel *upModel = [[IAAAuChUploadPicModel alloc] initWithBusiId:self.taskItem.busiId
                                                                             token:IAA_APP_DELEGATE.token
                                                                   AuChDetailModel:self.auChModel];
//    NSDictionary *jsonStr = [upModel yy_modelToJSONObject];   // 这里要对数组做特殊处理
    NSDictionary *pars = @{@"acceptId" : upModel.acceptId,
                           @"token"    : upModel.token,
                           @"osName"   : upModel.osName,
                           @"contentId": upModel.contentId,
                           @"foList"   : [upModel.foList yy_modelToJSONString]};
    
    NSString *urlStr = [IAAUrlProtocolMerge appFileImgUploadImg];
    NSLog(@"上传照片时的参数%@", pars);
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeDeterminate;
    hud.detailsLabelText = @"上传图片中...";
    [XDAFHttpRequest POST:urlStr parameters:pars progress:^(NSProgress * _Nonnull uploadProgress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = uploadProgress.fractionCompleted;
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:NO];
        NSLog(@"上传照片返回%@", responseObject);
        if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC]) {
//            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"照片上传成功"];
            [self.auChModel configNeedUploadFlag:NO];   //上传成功，置位上传标志位为已经上传
            [self requestCommitTask:commitFlag];
        }else{
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"resultMsg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传照片返回%@", error);
        [hud hide:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

// 审核通过、申通不通过
- (void)requestCommitTask:(BOOL)commitFlag {
    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckCommitTask];
    NSMutableDictionary *mPars = [self.commitModel yy_modelToJSONObject];
    // 审核通过标志、密码
    mPars[@"commitFlag"] = @(commitFlag);
    mPars[@"password"] = [self.pwdTextField.text xd_md5L32String];
    if (self.phoneNumTextField.text.length) { // 二审通过时需要的参数
        mPars[@"verifyCode"] = self.phoneNumTextField.text; // 手机验证码
    }

    NSLog(@"提交审核时的参数%@", mPars);
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [XDAFHttpRequest POST:urlStr parameters:mPars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:NO];
        NSLog(@"提交审核返回%@", responseObject);
        if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC]) {
            MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"resultMsg"]];
            temp.completionBlock = ^(){
                if (self.auChSureHandle) {
                    self.auChSureHandle(commitFlag ? AuChSureResultPass : AuChSureResultNotPass);
                    self.auChSureHandle = nil;
                }
                [self dismissViewControllerAnimated:YES completion:nil];
            };
        }else{
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"resultMsg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"提交审核失败%@", error);
        [hud hide:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

@end
